package tech.mhuang.pacebox.springboot.autoconfiguration.kaptcha;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.text.TextProducer;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 验证码生成器
 *
 * @author mhuang
 * @since 1.0.0
 */
public class KaptchaTextCreator extends DefaultKaptcha implements TextProducer {

    private final static ThreadLocalRandom LOCAL_RANDOM = ThreadLocalRandom.current();

    @Override
    public String createText() {
        int one = LOCAL_RANDOM.nextInt(10);
        int two = LOCAL_RANDOM.nextInt(10);
        int random = LOCAL_RANDOM.nextInt(4) % 4;
        StringBuilder strBuilder = new StringBuilder();
        String operator;
        int result;
        if (random == 0) {
            operator = "+";
            result = one + two;
        } else if (random == 1) {
            operator = "-";
            result = one - two;
        } else if (random == 2) {
            operator = "*";
            result = one * two;
        } else {
            if (two == 0) {
                two = 1;
            }
            result = one / two;
            operator = "/";
        }
        strBuilder.append(one).append(operator).append(two).append("=?@").append(result);
        return strBuilder.toString();
    }

    @Override
    public String getText() {
        return createText();
    }
}